package com.tjvib.view.fragment;

import static com.tjvib.Constants.SUCCESS;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.tapadoo.alerter.Alerter;
import com.tjvib.Constants;
import com.tjvib.R;
import com.tjvib.base.BaseFragment;
import com.tjvib.util.LogUtil;
import com.tjvib.util.Manager.AppManager;
import com.tjvib.util.Manager.UserManager;
import com.tjvib.util.PayUtil;
import com.tjvib.util.PressUtil;
import com.tjvib.util.SharedPreferencesUtil;
import com.tjvib.util.ToastUtil;
import com.tjvib.util.retrofit.BaseResponse;
import com.tjvib.util.retrofit.RetrofitHelper;
import com.tjvib.view.activity.AboutActivity;
import com.tjvib.view.activity.BootingActivity;
import com.tjvib.view.activity.ChatActivity;
import com.tjvib.view.activity.InfoActivity;
import com.tjvib.view.activity.LoginActivity;
import com.tjvib.view.activity.MainActivity;
import com.tjvib.view.activity.OrderActivity;
import com.tjvib.view.activity.ReportActivity;
import com.tjvib.view.activity.SafeActivity;
import com.tjvib.view.dialog.HintDialog;
import com.tjvib.view.dialog.InputDialog;
import com.tjvib.view.dialog.LoadingDialog;
import com.tjvib.view.dialog.PrivacyDialog;
import com.tjvib.widget.AndroidScheduler;
import com.tjvib.widget.ItemGroup;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import pub.devrel.easypermissions.EasyPermissions;

public class MeFragment extends BaseFragment implements View.OnClickListener, EasyPermissions.PermissionCallbacks {

    private static String phone = "15840442559";

    private ImageView frag_me_iv_icon;
    private TextView frag_me_tv_name, frag_me_tv_identity, frag_me_tv_ana;
    private LinearLayout frag_me_ll_pack, frag_me_ll_vip, frag_me_ll_order;
    private ItemGroup frag_me_ig_safe, frag_me_ig_setting, frag_me_ig_contact, frag_me_ig_rep, frag_me_ig_about;
    private Button frag_me_btn_exit, frag_me_btn_del;


    private String[] sms_perms = new String[]{Manifest.permission.SEND_SMS, Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.RECEIVE_SMS, Manifest.permission.READ_SMS};

    private String[] call_perms = new String[]{Manifest.permission.CALL_PHONE, Manifest.permission.READ_PHONE_STATE};
    private int RC_CALL_PHONE = 225, RC_SEND_SMS = 226;

    @Override
    protected int getContentView() {
        return R.layout.fragment_me;
    }

    @Override
    protected void initView() {
        frag_me_iv_icon = getView().findViewById(R.id.frag_me_iv_icon);
        frag_me_iv_icon.setOnClickListener(this);

        frag_me_tv_name = getView().findViewById(R.id.frag_me_tv_name);
        frag_me_tv_name.setOnClickListener(this);

        frag_me_tv_identity = getView().findViewById(R.id.frag_me_tv_identity);

        frag_me_ll_pack = getView().findViewById(R.id.frag_me_ll_pack);
        frag_me_ll_pack.setOnClickListener(this);

        frag_me_ll_order = getView().findViewById(R.id.frag_me_ll_order);
        frag_me_ll_order.setOnClickListener(this);

        frag_me_ig_safe = getView().findViewById(R.id.frag_me_ig_safe);
        frag_me_ig_safe.setOnClickListener(this);

        /*frag_me_ig_setting = getView().findViewById(R.id.frag_me_ig_setting);
        frag_me_ig_setting.setOnClickListener(this);
        PressUtil.setPressChange(getView().getContext(), frag_me_ig_setting);*/

        frag_me_ig_contact = getView().findViewById(R.id.frag_me_ig_contact);
        frag_me_ig_contact.setOnClickListener(this);

        frag_me_ig_rep = getView().findViewById(R.id.frag_me_ig_rep);
        frag_me_ig_rep.setOnClickListener(this);

        frag_me_ig_about = getView().findViewById(R.id.frag_me_ig_about);
        frag_me_ig_about.setOnClickListener(this);

        frag_me_btn_exit = getView().findViewById(R.id.frag_me_btn_exit);
        frag_me_btn_exit.setOnClickListener(this);

        frag_me_btn_del = getView().findViewById(R.id.frag_me_btn_del);
        frag_me_btn_del.setOnClickListener(this);

        frag_me_tv_ana = getView().findViewById(R.id.frag_me_tv_ana);

        PressUtil.setPressChange(getContext(), frag_me_iv_icon, frag_me_ll_pack, frag_me_ll_order,
                frag_me_ig_safe, frag_me_ig_contact, frag_me_ig_rep, frag_me_ig_about);
    }

    @Override
    protected void initData() {
        Glide.with(getView().getContext())
                .load(UserManager.getInstance().getImage())
                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                .into(frag_me_iv_icon);

        frag_me_tv_name.setText(UserManager.getInstance().getUsername());
        frag_me_tv_ana.setText(getString(R.string.ui_analysis_trial, UserManager.getInstance().getAnalysisTrial()));
        frag_me_tv_identity.setText(UserManager.getInstance().isVip() ? "会员用户" : "普通用户");

        LoadingDialog loadingDialog = new LoadingDialog(getActivity());
        loadingDialog.showDialog(getActivity(), "正在更新用户信息…");
        RetrofitHelper.getInstance().create().get_info(String.valueOf(UserManager.getInstance().getUserId()))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidScheduler.mainThread())
                .subscribe(new Observer<BaseResponse>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseResponse value) {
                        loadingDialog.dismiss();
                        if (value.getCode() == SUCCESS) {
                            LogUtil.d(value.getMessage() + "\n" + value.getData());
                            String token = UserManager.getInstance().setInfo(String.valueOf(value.getData()));
                            if (!token.isEmpty())
                                SharedPreferencesUtil.saveToken(getActivity(), token);
                        } else {
                            LogUtil.e(value.getCode() + "\n" + value.getMessage() + "\n" + value.getData());
                            showErrorDialog(value.getMessage());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        loadingDialog.dismiss();
                        LogUtil.e("get_info" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.frag_me_ll_order) {
            startActivity(new Intent(getView().getContext(), OrderActivity.class));
        } else if (view.getId() == R.id.frag_me_ll_pack) {
            PayUtil.showProductDialog(MeFragment.this);
        } else if (view.getId() == R.id.frag_me_ig_safe) {
            startActivity(new Intent(getView().getContext(), SafeActivity.class));
        /*} else if (view.getId() == R.id.frag_me_ig_setting) {
            startActivity(new Intent(getView().getContext(), SettingActivity.class));*/
        } else if (view.getId() == R.id.frag_me_ig_contact) {
            String[] deviceChoose = new String[]{"拨打电话", "发送短信", "在线联系"};
            new AlertDialog.Builder(getActivity())
                    .setTitle("选择")
                    .setItems(deviceChoose, (dialogInterface, i) -> {
                        switch (i) {
                            case 0:
                                if (EasyPermissions.hasPermissions(getActivity(), call_perms)) {
                                    Intent intent = new Intent(Intent.ACTION_DIAL);
                                    intent.setData(Uri.parse("tel:" + phone));
                                    startActivity(intent);
                                } else {
                                    EasyPermissions.requestPermissions(getActivity(),
                                            "请授予APP拨打电话、设备信息权限，以便联系客服和反馈信息。",
                                            RC_CALL_PHONE, call_perms);
                                    Alerter.create(getActivity()).setTitle("拨打电话、设备信息权限说明").setText("用于联系客服和反馈信息").show();
                                }
                                break;
                            case 1:
                                if (EasyPermissions.hasPermissions(getActivity(), sms_perms)) {
                                    InputDialog inputDialog = new InputDialog(getActivity());
                                    inputDialog.showDialog(getActivity(), "联系客服", "",
                                            "短信内容", view1 -> {
                                                String content = inputDialog.getEtCon().getText().toString();
                                                if (!content.isEmpty()) {
                                                    SmsManager manager = SmsManager.getDefault();
                                                    ArrayList<String> strings = manager.divideMessage(content);
                                                    for (int i1 = 0; i1 < strings.size(); i1++)
                                                        manager.sendTextMessage(phone, null,
                                                                content, null, null);
                                                    ToastUtil.show("发送成功");
                                                    inputDialog.dismiss();
                                                } else
                                                    ToastUtil.show("手机号或内容不能为空");
                                            },
                                            view1 -> inputDialog.dismiss());
                                } else {
                                    EasyPermissions.requestPermissions(getActivity(),
                                            "请授予APP发送短信权限",
                                            RC_SEND_SMS, sms_perms);
                                    Alerter.create(getActivity()).setTitle("发送和查看信息权限说明").setText("用于联系客服和反馈信息").show();
                                }
                                break;
                            case 2:
                                startActivity(new Intent(getView().getContext(), ChatActivity.class));
                                break;
                        }
                    })
                    .create()
                    .show();
        } else if (view.getId() == R.id.frag_me_ig_rep) {
            startActivity(new Intent(getView().getContext(), ReportActivity.class));
        } else if (view.getId() == R.id.frag_me_ig_about) {
            startActivity(new Intent(getView().getContext(), AboutActivity.class));
        } else if (view.getId() == R.id.frag_me_btn_exit) {
            SharedPreferencesUtil.clearToken(getActivity());
            startActivity(new Intent(getView().getContext(), LoginActivity.class));
            AppManager.getInstance().finishOtherActivity(LoginActivity.class);
        } else if (view.getId() == R.id.frag_me_tv_name || view.getId() == R.id.frag_me_iv_icon) {
            startActivity(new Intent(getView().getContext(), InfoActivity.class));
        } else if (view.getId() == R.id.frag_me_btn_del) {
            HintDialog hintDialog = new HintDialog(getActivity());
            hintDialog.setConfirmText("仍要注销");
            hintDialog.showDialog(getActivity(), "警告", "注销账号将删除本账号的全部数据，请谨慎确认！",
                    v -> {
                        RetrofitHelper.getInstance().create()
                                .delete_user(""+UserManager.getInstance().getUserId())
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidScheduler.mainThread())
                                .subscribe(new Observer<BaseResponse>() {
                                        @Override
                                        public void onSubscribe(Disposable d) {

                                        }

                                        @Override
                                        public void onNext(BaseResponse value) {
                                            LogUtil.i(value.getCode()+" "+value.getMessage()+" "+value.getData());
                                            if(value.getCode() == Constants.SUCCESS){
                                                SharedPreferencesUtil.clearToken(getActivity());
                                                startActivity(new Intent(getActivity(), BootingActivity.class));
                                                AppManager.getInstance().finishOtherActivity(BootingActivity.class);
                                            }
                                        }

                                        @Override
                                        public void onError(Throwable e) {
                                            LogUtil.e(e.getMessage());
                                            ToastUtil.show(e.getMessage());
                                        }

                                        @Override
                                        public void onComplete() {

                                        }
                                    });
                        hintDialog.dismiss();
                    },
                    v -> hintDialog.dismiss());
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            ToastUtil.show("请您前往本手机设置手动开启权限");
        }
    }
}